package com.pureland.ucc.controller;

import com.pureland.common.entity.R;
import com.pureland.security.annotations.IgnoreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.*;
import java.security.Principal;
import java.util.Map;

/**
 * @projectName: pureland_cloud
 * @className: com.pureland.ucc.controller.OAuth2Controller
 * @description: OAuth2认证授权API
 * @author: tong.li
 * @createTime: 2020/11/27 10:29
 * @version: v1.0
 * @copyright: 版权所有 李彤 © 2020
 */
@RestController
@RequestMapping("/oauth")
public class OAuth2Controller {

    @Autowired
    private TokenEndpoint tokenEndpoint;

    /**
     * 获取token
     * @param principal
     * @param parameters
     * @return
     * @throws HttpRequestMethodNotSupportedException
     */
    @GetMapping("/token")
    public R getAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return R.ok(tokenEndpoint.getAccessToken(principal, parameters).getBody());
    }

    /**
     * 认证
     * @param principal
     * @param parameters
     * @return
     * @throws HttpRequestMethodNotSupportedException
     */
    @PostMapping("/token")
    public R postAccessToken(Principal principal, @RequestParam Map<String, String> parameters) throws HttpRequestMethodNotSupportedException {
        return R.ok((tokenEndpoint.postAccessToken(principal, parameters).getBody()));
    }

    @RequestMapping("/user")
    public Principal user(Principal user) {
        return user;
    }

    /**
     * 通过@IgnoreAuthorize注解忽略认证授权
     * @return
     */
    @IgnoreAuthorize
    @RequestMapping("/success")
    public R success(String oauthType, String code ) {
        if (StringUtils.isEmpty(oauthType)) {
            return R.fail("第三方授权登录配置错误,请联系管理员");
        }
        if (StringUtils.isEmpty(code)) {
            return R.fail("第三方授权登录失败");
        }
        return R.ok("success");
    }

}
